package com.hannesdorfmann.mosby3.sample.mvp.lce.containner;

import com.hannesdorfmann.mosby3.mvp.MvpQueuingBasePresenter;
import com.hannesdorfmann.mosby3.mvp.animator.AlphaAnimator;
import com.hannesdorfmann.mosby3.mvp.widget.CirleProgressImg;
import com.hannesdorfmann.mosby3.sample.ResourceTable;
import com.hannesdorfmann.mosby3.sample.mvp.CountriesAdapter;
import com.hannesdorfmann.mosby3.sample.mvp.CountriesErrorMessage;
import com.hannesdorfmann.mosby3.sample.mvp.CountriesPresenter;
import com.hannesdorfmann.mosby3.sample.mvp.CountriesView;
import com.hannesdorfmann.mosby3.sample.mvp.lce.SimpleCountriesPresenter;
import com.hannesdorfmann.mosby3.sample.mvp.model.CountriesAsyncLoader;
import com.hannesdorfmann.mosby3.sample.mvp.model.Country;
import com.hannesdorfmann.swiperefresh.refresh.IRefresh;
import com.hannesdorfmann.swiperefresh.refresh.SwipeRefreshLayout;
import com.hannesdorfmann.swiperefresh.refresh.TextOverComponent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorGroup;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.AbilityContext;
import ohos.global.resource.ResourceManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.List;

public class NotRetainingCountriesComponentOwner implements ComponentOwner, CountriesView, IRefresh.RefreshListener {
    private static final String TAG = "NotRetainingCountriesComponentOwner";
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0, TAG);

    private AbilityContext myContext;
    private ComponentContainer root;
    protected ListContainer listContainer;
    protected SwipeRefreshLayout contentView;
    Text errorView;
    CirleProgressImg loadingView;

    CountriesAdapter adapter;
    SimpleCountriesPresenter presenter;

    public NotRetainingCountriesComponentOwner(AbilityContext context) {
        myContext = context;
        init();
    }

    private void init() {

        LayoutScatter scatter = LayoutScatter.getInstance(myContext);
        root = (ComponentContainer) scatter.parse(ResourceTable.Layout_countries_list, null, false);


    }

    private void initComponent(){
        presenter = new SimpleCountriesPresenter();
        presenter.attachView(this);

        listContainer = (ListContainer) root.findComponentById(ResourceTable.Id_listView);
        contentView = (SwipeRefreshLayout) root.findComponentById(ResourceTable.Id_contentView);
        contentView.setVisibility(Component.HIDE);

        errorView = (Text) root.findComponentById(ResourceTable.Id_errorView);
        loadingView = (CirleProgressImg) root.findComponentById(ResourceTable.Id_loadingView);
        errorView.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                presenter.loadCountries(false);
            }
        });

        TextOverComponent overView = new TextOverComponent(myContext);
        contentView.setRefreshOverComponent(overView);
        contentView.setRefreshListener(this);
        contentView.setDisableRefreshScroll(true);

        adapter = new CountriesAdapter(myContext);
        listContainer.setItemProvider(adapter);
        presenter.loadCountries(false);
    }

    @Override
    public Component getComponent() {
        if(root == null){
            init();
        }
        return root;
    }

    @Override
    public void instantiateComponent() {
        initComponent();
    }

    @Override
    public void showLoading(boolean pullToRefresh) {
        errorView.setVisibility(Component.HIDE);
        loadingView.setVisibility(Component.VISIBLE);
    }

    @Override
    public void showContent() {
        contentView.refreshFinish();

        if (contentView.getVisibility() == Component.VISIBLE) {
            // No Changing needed, because contentView is already visible
            errorView.setVisibility(Component.HIDE);
            loadingView.setVisibility(Component.HIDE);
        } else {

            errorView.setVisibility(Component.HIDE);
            loadingView.setVisibility(Component.VISIBLE);

            final ResourceManager resourceManager = loadingView.getResourceManager();
            float translateInPixels = 0f;
            try {
                translateInPixels = resourceManager.getElement(ResourceTable.Float_lce_content_view_animation_translate_y).getFloat();
            } catch (Exception e) {
                System.err.println("err e:" + e.getStackTrace());
            }


            long durations = 800;
            AnimatorProperty contentFadeIn = new AlphaAnimator(0f, 1f);
            contentFadeIn.setDuration(durations);
            contentFadeIn.setTarget(contentView);

            AnimatorProperty loadingFadeOut = new AlphaAnimator(0f, 1f);
            loadingFadeOut.setDuration(800);
            loadingFadeOut.setTarget(loadingView);

            AnimatorProperty contentTranslateIn = contentView.createAnimatorProperty();
            contentTranslateIn.moveFromY(translateInPixels);
            contentTranslateIn.moveToY(0);
            contentTranslateIn.setDuration(durations);


            AnimatorGroup set2 = new AnimatorGroup();
            set2.runParallel(contentFadeIn, contentTranslateIn);
            set2.setDuration(durations);
            set2.setStateChangedListener(new Animator.StateChangedListener() {
                @Override
                public void onStart(Animator animator) {
                    contentView.setTranslationY(0);
                    contentView.setVisibility(Component.VISIBLE);
                }

                @Override
                public void onStop(Animator animator) {
                    loadingView.setVisibility(Component.HIDE);
                    loadingView.setAlpha(1f); // For future showLoading calls
                    contentView.setTranslationY(0);
                }

                @Override
                public void onCancel(Animator animator) {
                }

                @Override
                public void onEnd(Animator animator) {
                }

                @Override
                public void onPause(Animator animator) {
                }

                @Override
                public void onResume(Animator animator) {
                }
            });
            contentView.setVisibility(Component.VISIBLE);
            set2.start();



        }
    }

    @Override
    public void showError(Throwable e, boolean pullToRefresh) {
        contentView.refreshFinish();
        String msg = CountriesErrorMessage.get(e, pullToRefresh, myContext);

        if (pullToRefresh) {
            contentView.setVisibility(Component.VISIBLE);
            loadingView.setVisibility(Component.HIDE);
            if (myContext != null) {
                ToastDialog mToastDialog = new ToastDialog(myContext);
                mToastDialog.setText(msg);
                mToastDialog.setDuration(1000);
                mToastDialog.show();
            }
        } else {
            contentView.setVisibility(Component.HIDE);
            errorView.setText(msg);

            int durations = 1200;
            final ResourceManager resourceManager = loadingView.getResourceManager();

            loadingView.setVisibility(Component.VISIBLE);

            // Not visible yet, so animate the view in
            AnimatorGroup set = new AnimatorGroup();
            AnimatorProperty in = errorView.createAnimatorProperty();
            AnimatorProperty loadingOut = loadingView.createAnimatorProperty();
            in.alpha(1f);
            in.setDuration(durations);
            in.setDelay(durations);
            loadingOut.alpha(0f);
            loadingOut.setDuration(200);
            set.runSerially(in, loadingOut);

            set.setDelay(durations);
            set.setStateChangedListener(new Animator.StateChangedListener() {
                @Override
                public void onStart(Animator animator) {
                    loadingView.setVisibility(Component.VISIBLE);
                }

                @Override
                public void onStop(Animator animator) {
                    errorView.setVisibility(Component.VISIBLE);
                    loadingView.setVisibility(Component.HIDE);
                }

                @Override
                public void onCancel(Animator animator) {
                }

                @Override
                public void onEnd(Animator animator) {
                }

                @Override
                public void onPause(Animator animator) {
                }

                @Override
                public void onResume(Animator animator) {
                }
            });
            set.start();
        }
    }

    public void setData(List<Country> data) {
        HiLog.error(LABEL, "setData ");
        adapter.setCountries(data);
        adapter.notifyDataChanged();
    }

    @Override
    public void loadData(boolean pullToRefresh) {
        presenter.loadCountries(true);
    }

    public List<Country> getData() {
        return adapter == null ? null : adapter.getCountries();
    }

    @Override
    public void onRefresh() {

        if(loadingView != null){
            loadingView.setVisibility(Component.HIDE);
        }
        loadData(true);
    }

    @Override
    public boolean enableRefresh() {
        return true;
    }

}
